package sjq.com.radar;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.text.format.DateFormat;
import android.view.View;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Locale;

/**
 * Created by chengengsen on 2016/8/10.
 */
public class SaveUtils {

    public  static Bitmap getBitmap(View view) {

        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        // Bind a canvas to it
        Canvas canvas = new Canvas(bitmap);
        // Get the view's background
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null)
            // has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
        else
            // does not have background drawable, then draw white background on
            // the canvas
            canvas.drawColor(Color.WHITE);
        // draw the view on the canvas
        view.draw(canvas);
        // return the bitmap
        return bitmap;
    }


    public static void saveToPath(Bitmap bitmap) {

        Bitmap b = bitmap;
        OutputStream stream = null;
        String name = DateFormat.format("yyyyMMdd_HHmmss",
                Calendar.getInstance(Locale.CHINA))
                + ".jpg";

        File file = new File(getSDPath()+"/JSZYCE");
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            stream = new FileOutputStream(file.getPath()+"/"+name);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                stream.flush();
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取SD卡根目录
        }else{
            sdDir = Environment.getRootDirectory();
        }
        return sdDir.toString();
    }



}
